<template>
  <div class="home">
    <van-nav-bar title="购物袋" left-arrow>
      <template #left>
        <!-- <Back /> -->
      </template>
      <template #right>
        <div
          v-if="shopMessage.length === 0 ? false : true"
          @click="methods.goDelete"
          v-text="isEdit ? '完成' : '编辑'"
        ></div>
      </template>
    </van-nav-bar>
    <div class="shopbag-img">
      <img class="head-img" src="@/assets/images/shopbag_bg.png" alt="" />
    </div>
    <van-checkbox-group v-model="chekcedList" ref="checkboxGroup">
      <van-swipe-cell v-for="(v, i) in shopMessage" :key="i">
        <div class="check-box">
          <van-checkbox :name="i" @click="methods.isCheckAll" />
        </div>
        <van-card
          :price="v.price"
          :desc="v.enname"
          :title="v.name"
          @click-thumb="methods.goShopMes(i)"
        >
          <template #thumb>
            <div class="thumb_img_box">
              <img :src="v.image_url" :alt="v.name" class="thumb_img" />
            </div>
          </template>
          <template #tags>
            <div class="shop-rule">{{ v.rule }}</div>
          </template>
          <template #footer>
            <van-button
              size="mini"
              @click="methods.reduce(i)"
              :class="v.quantity > 1 ? 'allow' : ''"
            >
              -
            </van-button>
            <span class="shop-num">{{ v.quantity }}</span>
            <van-button
              size="mini"
              @click="methods.add(i)"
              :class="v.quantity < 99 ? 'allow' : ''"
            >
              +
            </van-button>
          </template>
        </van-card>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="methods.deleteOne(i)"
          />
        </template>
      </van-swipe-cell>
    </van-checkbox-group>

    <van-empty
      description="购物车空空如也"
      v-show="shopMessage.length === 0 ? true : false"
    >
      <van-button
        round
        type="danger"
        class="bottom-button"
        @click="methods.goMenu"
      >
        {{ !isLogin ? '去登录' : '去菜单看看' }}
      </van-button>
    </van-empty>

    <div v-if="shopMessage.length === 0 ? false : true">
      <div v-show="!isEdit">
        <van-submit-bar
          :price="totalPrice"
          button-text="提交订单"
          button-color="rgb(12,52,186)"
          @submit="methods.goOrderSubmit"
        >
          <van-checkbox v-model="checkedAll" @click="methods.checkAll"
            >全选</van-checkbox
          >
        </van-submit-bar>
      </div>

      <div v-show="isEdit">
        <van-submit-bar
          button-text="删除选择"
          button-color="rgb(238,10,36)"
          @submit="methods.deleteChecked"
        >
          <van-checkbox v-model="checkedAll" @click="methods.checkAll"
            >全选</van-checkbox
          >
        </van-submit-bar>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
// import Back from '@/components/Back.vue'
import { GET, POST, postFormData } from '@/api'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import { getToken } from '@/utils/token'
const router = useRouter()

const shopMessage = ref<any[]>([])
const isLogin = !!getToken()
const chekcedList = ref<number[]>([])
const checkedAll = ref(false)
const totalPrice = ref(0)
const isEdit = ref(false)
const checkboxGroup = ref()

const methods = {
  reduce(i) {
    if (shopMessage.value[i].quantity > 1) {
      shopMessage.value[i].quantity--
      methods.priceCount()
    }
  },
  add(i) {
    if (shopMessage.value[i].quantity < 99) {
      shopMessage.value[i].quantity++
      methods.priceCount()
    }
  },
  getShopMessage(num: Nullable<number | string> = 0) {
    if (!isLogin) {
      return
    }
    GET({
      url: '/shop/list'
    })
      .then((res) => {
        console.log({ res })
        shopMessage.value =
          res.data?.list?.map((item) => {
            return {
              ...item,
              image_url: import.meta.env.VITE_APP_PROXY_URL + item.image_url
            }
          }) || []
        for (let j = 0; j < chekcedList.value.length; j++) {
          if (chekcedList.value[j] === num) {
            chekcedList.value.splice(j, 1)
            j--
          }
          if (chekcedList.value[j] > Number(num)) {
            chekcedList.value[j]--
          }
        }

        methods.priceCount()
        methods.isCheckAll()
      })
      .catch((err) => {
        console.error(err)
      })
  },
  checkAll() {
    if (checkedAll.value) {
      checkboxGroup.value?.toggleAll(true)
    } else {
      checkboxGroup.value?.toggleAll(false)
    }
    methods.priceCount()
  },
  isCheckAll() {
    if (chekcedList.value.length < shopMessage.value.length) {
      checkedAll.value = false
    } else {
      checkedAll.value = true
      if (shopMessage.value.length === 0) {
        checkedAll.value = false
      }
    }
    methods.priceCount()
  },
  priceCount() {
    let total = 0
    chekcedList.value.forEach((v) => {
      total += shopMessage.value[v].price * shopMessage.value[v].quantity
    })
    totalPrice.value = total * 100
  },
  goDelete() {
    isEdit.value = !isEdit.value
  },
  deleteChecked() {
    const ids: number[] = []
    for (let i = 0; i < chekcedList.value.length; i++) {
      ids.push(shopMessage.value[chekcedList.value[i]].content_id)
    }

    chekcedList.value = []
    checkedAll.value = false
    methods.priceCount()

    postFormData({
      url: '/shop/remove',
      params: {
        ids: ids.join(',')
      }
    })
      .then(() => {
        methods.getShopMessage()
      })
      .catch((err) => {
        console.error(err)
      })
  },
  deleteOne(i) {
    const index = String(i)
    const ids: number[] = []
    ids.push(shopMessage.value[index].content_id)

    postFormData({
      url: '/shop/remove',
      params: {
        ids: ids.join(',')
      }
    })
      .then(() => {
        methods.getShopMessage(index)
        showSuccessToast('删除成功')
      })
      .catch((err) => {
        console.error(err)
      })
  },
  goShopMes(i) {
    const pid = shopMessage.value[i].content_id

    router.push({ name: 'ShopMes', query: { pid } })
  },
  goOrderSubmit() {
    const ids: number[] = []
    for (let i = 0; i < chekcedList.value.length; i++) {
      ids.push(shopMessage.value[chekcedList.value[i]].id)
    }
    if (ids.length > 0) {
      router.push({
        name: 'OrderSubmit',
        query: {
          ids: ids.join(',')
        }
      })
    } else {
      showToast('请添加商品')
    }
  },
  goMenu() {
    if (!isLogin) {
      methods.goLogin()
    } else {
      router.push({ name: 'Menu' })
    }
  },
  goLogin() {
    router.push({ name: 'Login' })
  }
}

onMounted(() => {
  methods.getShopMessage()
})

/** 离开页面保存信息 */
onBeforeRouteLeave((_to, _from, next) => {
  if (shopMessage.value.length > 0) {
    POST({
      url: '/shop/edit',
      params: {
        data: shopMessage.value.map((item) => ({
          quantity: item.quantity,
          content_id: item.id
        }))
      }
    })
      .then(() => {
        showToast('商品配置已自动保存')
      })
      .catch((err) => {
        console.error(err)
      })
      .finally(() => {
        next()
      })
  } else {
    next()
  }
})
</script>

<style lang="less" scoped>
.home {
  padding-bottom: 110px;
}
.shopbag-img {
  width: 100%;
  img {
    width: 100%;
  }
}

.delete-button {
  height: 100%;
}
:deep(.van-card__footer) {
  position: absolute;
  right: 16px;
  bottom: 8px;
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
:deep(.van-button--mini) {
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  border-radius: 50%;
  background-color: #ddd;
  border: 1px solid #bbb;
  font-size: 18px;
}
.shop-num {
  font-size: 16px;
}
.allow {
  background-color: rgb(12, 52, 186);
  color: #fff;
}
:deep(.van-card) {
  padding-left: 40px;
}
.check-box {
  position: absolute;
  left: 10px;
  top: 42px;
  // background-color: red;
  z-index: 9;
}
:deep(.van-submit-bar) {
  bottom: 50px;
  border-bottom: 1px solid #eee;
}
:deep(.van-submit-bar__bar) {
  justify-content: space-between;
}
:deep(.van-nav-bar) {
  position: sticky;
  top: 0;
}
:deep(.van-card__title) {
  font-size: 14px;
}
:deep(.van-card__desc) {
  color: #999;
}
.shop-rule {
  color: #aaa;
}
.bottom-button {
  background-color: rgb(12, 52, 186);
  border: 1px solid rgb(12, 52, 186);
}
:deep(.van-swipe-cell__wrapper) {
  position: relative;
}
.thumb_img_box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.thumb_img {
  width: 100%;
}
</style>
